package com.lzy.arithmetic;

/**
 * Author: lzy
 * Date:   2020/06/10 16:36
 * Description:
 **/
public class 快速排序 {

    public static void main(String[] args) {
        int[] array = new int[]{67, 34, 2, 56, 89, 46, 33, 23};
        sortArray(array);
        for (int i : array) {
            System.out.print(i + " ");
        }
    }

    public static int[] sortArray(int[] nums) {
        sortDG(nums, 0, nums.length - 1);
        return nums;
    }

    public static void sortDG(int[] num, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = partition(num, left, right);
        sortDG(num, left, mid - 1);
        sortDG(num, mid + 1, right);
    }

    public static int partition(int[] arr, int startIndex, int endIndex) {
        int piviot = arr[startIndex];
        int left = startIndex;
        int right = endIndex;
        while (left != right) {
            while (left < right && arr[right] > piviot) {
                right--;
            }
            while (left < right && arr[left] <= piviot) {
                left++;
            }
            if (left < right) {
                int p = arr[left];
                arr[left] = arr[right];
                arr[right] = p;
            }
        }
        //piviot和指针重合点交换
        int p = arr[startIndex];
        arr[startIndex] = arr[left];
        arr[left] = p;

        return left;
    }
}
